import { build } from 'esbuild';
import { writeFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

async function bundleAdapter(adapterName) {
  try {
    const result = await build({
      entryPoints: [join(__dirname, `../src/adapters/${adapterName}/adapter-runtime.ts`)],
      bundle: false,
      write: false,
      format: 'esm',
      platform: 'browser',
      target: 'es2020',
      minify: false,
    });

    const bundledCode = result.outputFiles[0].text;
    const serializedCode = JSON.stringify(bundledCode);

    const outputContent = `// This file is auto-generated by scripts/bundle-adapter.js
// Do not edit directly - modify adapter-runtime.ts instead

export const ADAPTER_RUNTIME_SCRIPT = ${serializedCode};
`;

    const outputTsPath = join(__dirname, `../src/adapters/${adapterName}/adapter-runtime.bundled.ts`);
    writeFileSync(outputTsPath, outputContent);
    console.log(`✅ Successfully bundled ${adapterName} adapter runtime`);
  } catch (error) {
    console.error(`❌ Failed to bundle ${adapterName} adapter runtime:`, error);
    process.exit(1);
  }
}

await bundleAdapter('appssdk');
await bundleAdapter('mcp-apps');
